package com.dds.system.service.union.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dds.common.config.AppInterfaceConfig;
import com.dds.common.utils.DateUtils;
import com.dds.common.utils.StringUtils;
import com.dds.common.utils.http.HttpUtils;
import com.dds.common.utils.sign.Md5Utils;
import com.dds.system.mapper.admin.AdminUserOperationChildMapper;
import com.dds.system.mapper.admin.AdminUserOperationMapper;
import com.dds.system.service.admin.impl.AdminOperationShopProfitServiceImpl;
import com.dds.system.service.admin.impl.AdminUserOperationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dds.system.mapper.union.UnionShopIndexMapper;
import com.dds.system.domain.union.UnionShopIndex;
import com.dds.system.service.union.IUnionShopIndexService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 联盟商家Service业务层处理
 *
 * @author gaolianjie
 * @date 2021-03-31
 */
@Service
public class UnionShopIndexServiceImpl implements IUnionShopIndexService {
    @Autowired
    private UnionShopIndexMapper unionShopIndexMapper;

    @Autowired
    private AppInterfaceConfig appInterfaceConfig;

    @Autowired
    private AdminUserOperationServiceImpl adminUserOperationService;

    @Autowired
    private AdminOperationShopProfitServiceImpl adminOperationShopProfitService;

    /**
     * 查询联盟商家
     *
     * @param shopId 联盟商家ID
     * @return 联盟商家
     */
    @Override
    public UnionShopIndex selectUnionShopIndexById(String shopId) {
        return unionShopIndexMapper.selectUnionShopIndexById(shopId);
    }

    /**
     * 查询联盟商家列表
     *
     * @param unionShopIndex 联盟商家
     * @return 联盟商家
     */
    @Override
    public List<UnionShopIndex> selectUnionShopIndexList(UnionShopIndex unionShopIndex) {
        return unionShopIndexMapper.selectUnionShopIndexList(unionShopIndex);
    }

    /**
     * 新增联盟商家
     *
     * @param unionShopIndex 联盟商家
     * @return 结果
     */
    @Override
    public int insertUnionShopIndex(UnionShopIndex unionShopIndex) {
        unionShopIndex.setCreateTime(DateUtils.getNowDate());
        return unionShopIndexMapper.insertUnionShopIndex(unionShopIndex);
    }

    /**
     * 修改联盟商家
     *
     * @param unionShopIndex 联盟商家
     * @return 结果
     */
    @Override
    public int updateUnionShopIndex(UnionShopIndex unionShopIndex) {
        return unionShopIndexMapper.updateUnionShopIndex(unionShopIndex);
    }

    /**
     * 批量删除联盟商家
     *
     * @param shopIds 需要删除的联盟商家ID
     * @return 结果
     */
    @Override
    public int deleteUnionShopIndexByIds(String[] shopIds) {
        return unionShopIndexMapper.deleteUnionShopIndexByIds(shopIds);
    }

    /**
     * 删除联盟商家信息
     *
     * @param shopId 联盟商家ID
     * @return 结果
     */
    @Override
    public int deleteUnionShopIndexById(String shopId) {
        return unionShopIndexMapper.deleteUnionShopIndexById(shopId);
    }

    /**
     * 获取首页数据
     * @return 结果
     */
    @Override
    public Map<String, Integer> getIndexData() {
        String date = DateUtils.getDate();
        Map<String, String> params = new HashMap<>();
        params.put("submitTime", date);
        int submitCount = unionShopIndexMapper.getQueryCount(params);

        params.put("status", "13");
        int okCount = unionShopIndexMapper.getQueryCount(params);

        Map<String, Integer> returnData = new HashMap<>();
        returnData.put("submitCount", submitCount);
        returnData.put("okCount", okCount);

        return returnData;
    }

    /**
     * 获取商家审核列表数据
     * @param type 类型
     * @param shopName 商家名称
     * @param serverName 服务商名称
     * @param corpName 企业名称
     * @param legalPersonName 法人姓名
     * @return 结果
     */
    @Override
    public List<Map<String, Object>> selectExamineList(String type, String shopName, String serverName,
                                                       String corpName, String legalPersonName
    ) {
        List<String> status = new ArrayList<>();
        switch (type) {
            case "2":
                status.add("31");
                break;
            case "3":
                status.add("13");
                break;
            case "4":
                status.add("32");
                break;
            default:
                status.add("31");
                status.add("13");
                status.add("32");
        }

        return unionShopIndexMapper.selectExamineList(status, shopName, serverName, corpName, legalPersonName);

    }

    /**
     * 审核店铺
     * @param params 参数
     * @param adminUserId 后台用户id
     * @return 结果
     */
    @Override
    @Transactional
    public Map<String, Object> examineShop(String params, Long adminUserId) {
        Map paramsMap = JSON.parseObject(params, Map.class);
        Map<String, Object> data = new HashMap<>();

        UnionShopIndex shopIndex = unionShopIndexMapper.selectUnionShopIndexById(paramsMap.get("shopId").toString());
        // 修改运营中心开店数量
        String msg = adminUserOperationService.checkOpenShopNum(shopIndex.getServeUser());
        if (!msg.equals("true")) {
            data.put("status", false);
            data.put("msg", msg);

            return data;
        }

        // 调取接口，审核店铺
        Map<String, Object> apiParamsMap = new HashMap<>();
        apiParamsMap.put("backUserId", adminUserId);
        apiParamsMap.put("secret", Md5Utils.hash(paramsMap.get("shopId").toString() + "dds.com"));
        apiParamsMap.put("shopId", paramsMap.get("shopId").toString());
        apiParamsMap.put("result", paramsMap.get("type"));
        apiParamsMap.put("reason", paramsMap.get("desc"));

        StringBuffer apiParams = HttpUtils.formatParams(apiParamsMap);

        String result = HttpUtils.sendPost(appInterfaceConfig.getWebUrl() + "/rest/back/shop/verify", apiParams.toString());
        Map resMap = JSONObject.parseObject(result, Map.class);
        if (resMap == null) {
            data.put("status", false);
            data.put("msg", "请求失败");

            return data;
        }
        if (Integer.parseInt(resMap.get("code").toString()) != 200) {
            data.put("status", false);
            data.put("msg", resMap.get("msg"));

            return data;
        }

        // 拒绝审核
        if (paramsMap.get("type").equals("0")) {
            data.put("status", true);
            data.put("msg", "拒绝审核成功");
            return data;
        }

        // 创建人店比表记录
        adminOperationShopProfitService.createProfit(
                shopIndex.getServeUser(),
                paramsMap.get("shopId").toString()
        );

        data.put("status", true);
        data.put("msg", "审核成功");
        return data;
    }

    /**
     * 商家审核详情
     * @param shopId 商家id
     * @return 结果
     */
    @Override
    public Map<String, Object> selectUnionShopIndexByIdForExamine(String shopId) {
        Map<String, Object> data = unionShopIndexMapper.selectUnionShopIndexByIdForExamine(shopId);

        data.put("business_license_photo", appInterfaceConfig.getImgUrl() + data.get("business_license_photo"));
        data.put("business_bank_card_photo_back", appInterfaceConfig.getImgUrl() + data.get("business_bank_card_photo_back"));
        data.put("business_bank_card_photo_front", appInterfaceConfig.getImgUrl() + data.get("business_bank_card_photo_front"));

        data.put("legal_person_idcard_photo_front", appInterfaceConfig.getImgUrl() + data.get("legal_person_idcard_photo_front"));
        data.put("legal_person_idcard_photo_back", appInterfaceConfig.getImgUrl() + data.get("legal_person_idcard_photo_back"));

        data.put("image_a", appInterfaceConfig.getImgUrl() + data.get("image_a"));
        data.put("image_b", appInterfaceConfig.getImgUrl() + data.get("image_b"));
        data.put("image_c", appInterfaceConfig.getImgUrl() + data.get("image_c"));

        return data;
    }

    /**
     * 获取未定义运营人员列表
     * @return 数据
     */
    @Override
    public List<Map<String, Object>> selectNoOperationList() {
        return unionShopIndexMapper.selectNoOperationList();
    }

    /**
     * 店铺转移
     * @param params 参数
     * @return 结果
     */
    @Override
    public boolean changeShopOperation(Map<String, String> params) {
        String shopId = params.get("shopId");
        String userId = params.get("newUserId");

        // 创建新分润
        boolean profit = adminOperationShopProfitService.createProfit(userId, shopId);

        if (!profit) {
            return false;
        }

        UnionShopIndex shopIndex = unionShopIndexMapper.selectUnionShopIndexById(shopId);
        shopIndex.setServeUser(userId);

        unionShopIndexMapper.updateUnionShopIndex(shopIndex);

        return true;
    }
}
